package com.example.mouse_phone;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;

public class MouseMode extends Activity 
{
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		int currentOrientation = GetCurrentOrientation();//default orientation
		
		super.onCreate(savedInstanceState);
		
		
		
		//enable orientation saved in settings
		this.setRequestedOrientation(currentOrientation);
		
		setContentView(R.layout.activity_mouse_mode);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_mouse_mode, menu);
		return true;
	}
	
	public void ChangeOrientation(View view)
	{
		byte[] buffer = new byte[1];
		FileOutputStream fos;
		int currentOrientation = GetCurrentOrientation();
		
		//Change Orientation
		if(currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
			currentOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
		else
			currentOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
		
		//save new orientation settings
		try 
		{
			buffer = ("" + currentOrientation).getBytes();
			fos = openFileOutput("MousePhoneSettings", Context.MODE_PRIVATE);
			fos.write(buffer);
			fos.close();
			this.setRequestedOrientation(currentOrientation);		
		} 
		catch (Exception e1)
		{
			e1.printStackTrace();
		}
	}
	
	/* Input:
	 * Output: int currentOrientation
	 * Change: The private internal "MousePhoneSettings" file
	 * 
	 * This function will return the current "desired" orientation of the screen as saved in the 
	 * designated file. If the file does not exist, it will create one with default settings.
	 */
	public int GetCurrentOrientation()
	{
		FileOutputStream fos;
		FileInputStream fis;
		int currentOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;//default orientation
		byte[] buffer = new byte[1];
				
		//Read in saved settings
		try
		{
			fis = openFileInput("MousePhoneSettings");
			fis.read(buffer);
			currentOrientation = Integer.parseInt(new String(buffer)); 
			fis.close();
		}
		//File not found, therefore create a settings file and set default values
		catch(FileNotFoundException e)
		{
			try 
			{
				buffer = ("" + currentOrientation).getBytes();  
				fos = openFileOutput("MousePhoneSettings", Context.MODE_PRIVATE);
				fos.write(buffer);
				fos.close();
			} 
			catch (Exception e1)
			{
				e1.printStackTrace();
			}
		}
		catch(IOException e1)
		{
			e1.printStackTrace();
		}
		
		return currentOrientation;
	}

}
